package shop

import (
	"context"
	"fast-boot/app/model"
	"gorm.io/gorm"

	"fast-boot/app/api/admin/internal/svc"
	"fast-boot/app/api/admin/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type CategoryAttributeAddLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 新增类型-属性
func NewCategoryAttributeAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CategoryAttributeAddLogic {
	return &CategoryAttributeAddLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CategoryAttributeAddLogic) CategoryAttributeAdd(req *types.PmsCategoryAttributeForm) (resp *types.PmsCategoryFormResp, err error) {

	if err := l.svcCtx.GormClient.GormDb.Transaction(func(tx *gorm.DB) error {
		if err := tx.Where("type = ?", req.Type).
			Where("category_id = ?", req.CategoryId).
			Delete(&model.PmsCategoryAttributeModel{}).Error; err != nil {
			return err
		}

		for _, name := range req.Attributes {
			if err := tx.FirstOrCreate(&model.PmsCategoryAttributeModel{}, &model.PmsCategoryAttributeModel{
				Name:       name,
				Type:       int8(req.Type),
				CategoryId: req.CategoryId,
			}).Error; err != nil {
				return err
			}
		}
		return nil
	}); err != nil {
		return nil, err
	}
	return &types.PmsCategoryFormResp{}, nil
}
